import { PlayDetailComponent } from './detail/detail.component';
import { DialogService } from './../service/dialog.service';
import { Component, OnInit, ChangeDetectorRef, ViewChild } from '@angular/core';
import { MdPaginator, MdSnackBar, MD_DIALOG_DATA } from "@angular/material";
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { DataSource } from '@angular/cdk/collections';
import { ApiServiceService } from '../api.service'
import { MdDialog, MdDialogRef } from '@angular/material';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'paly-log',
  templateUrl: './paly-log.component.html',
  styleUrls: ['./paly-log.component.css']
})
export class PalyLogComponent implements OnInit {
  sid;
  content = [];
  constructor(private apiService: ApiServiceService,
    private changeDetectorRef: ChangeDetectorRef,
    public snackBar: MdSnackBar,
    public dialog: MdDialog,
    public dialogService: DialogService
  ) {
  }

  ngOnInit() {
    this.sid = sessionStorage.id;
    this.dataSource = new SoundSourceDataSource(this.soundSourceDatabase, this.paginator);
    this.changeDetectorRef.detectChanges();
    this.allSelectedFlag = false;
    this.apiService.getEBMLogs().subscribe(res => {
      if (res.success) {
        // 按发送事件排序
        this.content = res.data.sort((a,b) => {
          let c =  new Date(b.SendTime).getTime()- new Date(a.SendTime).getTime()
          return c
        })
        // this.content = res.data;
        this.soundSourceDatabase.refreshData(this.content);
      }
    })
  }

  displayedColumns = [/*'no',*/ "check",'EBMID', 'SentTime', 'SenderName', 'MsgTitle', 'MsgDesc',"BrdStateDesc","operator"];
  soundSourceDatabase = new SoundSourceDatabase();
  dataSource: SoundSourceDataSource | null;
  allSelectedFlag: boolean;

  @ViewChild(MdPaginator) paginator: MdPaginator;



  detail(row) {
    this.dialogService.openConfirm(PlayDetailComponent, {
      data: row
    })
  }

  SelectAll(e) {
      this.content.map(item => item.checked = e.checked)
  }

  report() {
    let data = this.content.filter(item => item.checked).map(item => item._id)
    if(data.length === 0){
      return this.openSnackBar("请选择上报的记录", 'OK');
    }
    this.apiService.reportPlayLog(data).subscribe(res => {
      if(res.success) {
         this.openSnackBar("上报成功", 'OK');
      }
    })
  }

  stop(row) {
    this.apiService.stopEbm(row.EBMID).subscribe(res => {
      if(res.success) {
        this.openSnackBar("停止成功", 'OK');
      }
    })
  }
  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 3000,
    });
  }

}



/*export interface SoundSourceData {
 deleteFlag:boolean;
 no:string;
 acaption:string;
 acontent:string;
 uid:string;
 isChecked:boolean,
 }*/
export interface SoundSourceData {
  // deleteFlag:boolean;
  // no:string;
  EBMID: string;
  SentTime: string;
  SenderName: string;
  MsgTitle: string;
  MsgDesc: string;
  BrdStateDesc: string;
  operator?: any;
}

export class SoundSourceDatabase {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<SoundSourceData[]> = new BehaviorSubject<SoundSourceData[]>([]);

  get data(): SoundSourceData[] {
    return this.dataChange.value;
  }


  constructor() {
    // Fill up the database with 100 users.
    var _a: SoundSourceData[] = [
      // {
      //   "deleteFlag": false,
      //   "no": "1",
      //   "acaption": "网络节目源1",
      //   "acontent": "7001",
      //   "uid": "admin",
      //   "isChecked": false
      //
      // }
    ];
    this.dataChange.next(_a);

    // for (var i = 0; i < 100; i++) {
    //   this.addUser();
    // }
  }


  refreshData(array) {
    array.forEach(function (item, index) {
      item.no = index + 1;
    })
    this.dataChange.next(<SoundSourceData[]>array);
  }


}

export class SoundSourceDataSource extends DataSource<any> {
  constructor(private _soundSourceDatabase: SoundSourceDatabase, private _paginator: MdPaginator) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<SoundSourceData[]> {
    const displayDataChanges = [
      this._soundSourceDatabase.dataChange,
      this._paginator.page,
    ];
    return Observable.merge(...displayDataChanges).map(() => {
      const data = this._soundSourceDatabase.data.slice();

      // Grab the page's slice of data.
      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
      return data.splice(startIndex, this._paginator.pageSize);
    });

  }

  disconnect() {
  }
}
